package control;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.NewsDao;
import dao.TopicDao;
import pojo.News;
import pojo.Topic;
import utils.PageUtil;

public class DoInitialHomePage extends HttpServlet {

	public DoInitialHomePage() {
		super();
	}

	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		Integer tid = null, pageNo;
		try {
			tid = Integer.parseInt(request.getParameter("tid"));
		} catch (Exception e) {
		}
		pageNo = request.getParameter("pageNo") == null ? 1 : Integer.parseInt(request.getParameter("pageNo"));
		request.setAttribute("tid", tid);
		request.setAttribute("pag", pageNo);

		List<News> newsGN = NewsDao.doSearchTopX(1);
		request.setAttribute("newsGN", newsGN);

		List<News> newsGJ = NewsDao.doSearchTopX(2);
		request.setAttribute("newsGJ", newsGJ);

		List<News> newsYL = NewsDao.doSearchTopX(3);
		request.setAttribute("newsYL", newsYL);

		List<Topic> topics = TopicDao.doTopicSearch();
		request.setAttribute("topics", topics);

		PageUtil<News> pageutil = NewsDao.doPageSearch(pageNo, tid);
		request.setAttribute("pageutil", pageutil);
		request.getRequestDispatcher("/WEB-INF/jsp/index.jsp").forward(request, response);

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the POST method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	public void init() throws ServletException {
		// Put your code here
	}

}
